#
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2023 Ricardo Pardini <ricardo@pardini.net>
# This file is a part of the Armbian Build Framework https://github.com/armbian/build/
#

# Add package to image
function extension_prepare_config__add_uboot_menu_pkg() {
	add_packages_to_image "u-boot-menu" # @TODO: using Debian/Ubuntu default package. Armbian will need to provide its own, later, so we can customize.
}

# Configure the package
function pre_umount_final_image__configure_uboot_menu() {
	# Configure common for all boards
	cat <<- UBOOT_MENU_CONFIGURATION_COMMON > "${MOUNT}/etc/default/u-boot"
		## /etc/default/u-boot - configuration file for u-boot-update(8)
		# Generated by Armbian for board ${BOARD} ${BRANCH}
		U_BOOT_UPDATE="true"
		U_BOOT_ALTERNATIVES="default recovery"
		U_BOOT_MENU_LABEL="Armbian"
		U_BOOT_TIMEOUT="10"
		U_BOOT_FDT_DIR="/usr/lib/linux-image-"
	UBOOT_MENU_CONFIGURATION_COMMON

	if [[ "${BOOT_FDT_FILE}" != "" && "${EXTLINUX_SPECIFIC_FDT:-"yes"}" != "no" ]]; then
		cat <<- UBOOT_MENU_CONFIGURATION_DTB >> "${MOUNT}/etc/default/u-boot"
			U_BOOT_FDT="${BOOT_FDT_FILE}"
		UBOOT_MENU_CONFIGURATION_DTB
	fi

	cat <<- UBOOT_MENU_CONFIGURATION_CMDLINE >> "${MOUNT}/etc/default/u-boot"
		U_BOOT_PARAMETERS="${SRC_CMDLINE:-"loglevel=7 console=ttyS0"}"
	UBOOT_MENU_CONFIGURATION_CMDLINE

	# Set EXTLINUX_UINITRD=no force usage of normal initrd even when NAME_INITRD is uInitrd
	if [[ "${NAME_INITRD}" == "uInitrd" && "${EXTLINUX_UINITRD:-"yes"}" == "yes" ]]; then
		cat <<- UBOOT_MENU_CONFIGURATION_INITRD >> "${MOUNT}/etc/default/u-boot"
			U_BOOT_INITRD="uInitrd" # Force usage of /boot/uInitrd-<version> as initrd
		UBOOT_MENU_CONFIGURATION_INITRD
	fi
}

# Run it, very late in the game, so all kernels all already installed.
function pre_umount_final_image__995_run_uboot_update() {
	local chroot_target="${MOUNT}"

	# Mount the chroot...
	mount_chroot "$chroot_target/" # this already handles /boot/efi which is required for it to work.

	display_alert "Creating u-boot-menu..." "u-boot-update" "info"
	chroot_custom "$chroot_target" u-boot-update || {
		exit_with_error "u-boot-update failed!"
	}

	# Let's show the produced /boot/extlinux/extlinux.conf
	display_alert "u-boot-menu configuration" "extlinux.conf" "info"
	run_tool_batcat --file-name "/boot/extlinux/extlinux.conf" "${MOUNT}/boot/extlinux/extlinux.conf"

	umount_chroot "$chroot_target/"
}
